package cn.ham.ms.aop;

import cn.ham.ms.config.DynamicDataSourceHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

@Aspect
@EnableAspectJAutoProxy(exposeProxy=true,proxyTargetClass=true)
@Component
public class DynamicDbAspect implements PriorityOrdered{

    private static Logger logger = LoggerFactory.getLogger(DynamicDbAspect.class);

    @Pointcut("execution(* cn.ham.ms.service..*.*(..)) && @annotation(cn.ham.ms.annotation.MasterDb)")
    public void masterDb(){}
    @Pointcut("execution(* cn.ham.ms.service..*.*(..)) && @annotation(cn.ham.ms.annotation.SlaveDb)")
    public void slaveDb(){}



    @Before("slaveDb()")
    public void setSlaveDb() {
        logger.info("aop use slave.");
        DynamicDataSourceHolder.setDbType(DynamicDataSourceHolder.DbType.slave);
    }

    @Before("masterDb()")
    public void setMasterDb() {
        logger.info("aop use master.");
        DynamicDataSourceHolder.setDbType(DynamicDataSourceHolder.DbType.master);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
